<?php

/**
 * 手机短信验证码
 * File Name：SnsVerification.php
 * File Encoding：UTF-8
 * File New Time：2014-8-5 10:06:28
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class SnsVerification {

    //错误信息
    protected $error = NULL;
    //类型
    protected $type = NULL;
    //手机
    protected $moblie = NULL;
    //验证码有效期
    protected $valid = 3600;

    /**
     * 链接服务
     * @staticvar null $handier
     * @return \SnsVerification
     */
    static public function getInstance() {
        static $handier = NULL;
        if (empty($handier)) {
            $handier = new SnsVerification();
        }
        return $handier;
    }

    /**
     * 获取最近的一条错误信息
     * @return string
     */
    public function getError() {
        return $this->error;
    }

    /**
     * 发送验证码
     * @param type $moblie 手机号
     * @param string $type 验证码类型
     * @param string $content 短信内容，{code} 会被替换成真实的验证码
     * @return boolean
     */
    public function send($moblie, $type = 'SnsVerification', $content = '') {
        if (empty($moblie)) {
            $this->error = '手机号不能为空！';
            return false;
        }
        $this->moblie = $moblie;
        $this->type = $type;
        $key = $this->getKey();
        //检查已有的验证码是否失效
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $cache = mt_rand(111111, 999999);
            Yii::app()->cache->set($key, $cache, $this->valid);
        }
        if (empty($content)) {
            $content = "妈咪街手机短信验证，您的验证码为：{$cache}，请不要泄漏给其他人，有效期1小时。";
        } else {
            $content = str_replace('{code}', $cache, $content);
        }
        Sns::getInstance()->send($moblie, $content);
        return $cache;
    }

    /**
     * 验证码验证
     * @param type $code 接收到的验证码
     * @param type $moblie 手机
     * @param type $type 验证码类型
     * @return boolean
     */
    public function verification($code, $moblie, $type = 'SnsVerification') {
        if (empty($code)) {
            $this->error = '验证码不能为空！';
            return false;
        }
        if (empty($moblie)) {
            $this->error = '手机号不能为空！';
            return false;
        }
        $this->moblie = $moblie;
        $this->type = $type;
        $key = $this->getKey();
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $this->error = '验证码已经失效！';
            return false;
        }
        if ($cache == $code) {
            Yii::app()->cache->delete($key);
            return true;
        }
        $this->error = '验证码不正确！';
        return false;
    }

    /**
     * 返回key
     * @return type
     */
    protected function getKey() {
        return md5($this->moblie . $this->type . $this->valid);
    }

}
